package com.example.demo.controller;

import com.example.demo.domain.User;
import com.example.demo.security.UserPermissionEvaluator;
import com.example.demo.service.UserService;
import com.example.demo.util.ParseUsername;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONArray;
import net.sf.json.JSONException;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

@RestController
@CrossOrigin
@Slf4j
public class ApiController {
    @Autowired
    private UserService userService;

    private JSONArray list;

    @Autowired
    BCryptPasswordEncoder bCryptPasswordEncoder;

    @Autowired
    UserPermissionEvaluator userPermissionEvaluator;

    //调用login的测试方法
    @GetMapping("/testLogin")
    public String testLogin() {
        userService.login("wangze", "wangze");
        return "调用userService中login方法的测试方法";
    }

    //调用loginSuccess的测试方法
    @GetMapping("/testLoginSuccess")
    public String testLoginSuccess() {
        User user = new User();
        user.setUsername("wangze");
        user.setPassword("wangze");
        List<Object> list = new ArrayList<>();
        list.add("0");
        list.add(1);
        list.add("2");
        list.add("3");
        list.add("4");
        list.add("5");
        list.add("6");
        list.add(7);
        list.add(8);
        return loginSuccess(list, user);
    }

    //调用loginSuccess的测试方法
    @GetMapping("/testLoginFail")
    public String testLoginFail() {
        User user = new User();
        user.setUsername("wangze");
        user.setPassword("wangze11");
        return loginFail(user);
    }

    //调用authorizeHandler的测试方法
    @GetMapping("/testAuthorizeHandler")
    public String testAuthorizeHandler(){
        userPermissionEvaluator.authorizedHandler();
        return "调用方法authorizeHandler()";
    }

    //调用denyHandler的测试方法
    @GetMapping("/testDenyHandler")
    public String testDenyHandler(){
        userPermissionEvaluator.denyHandler();
        return "调用方法denyHandler()";
    }


    /**
     * @Description: 用户登录
     * @Param: users: 前端传递的用户信息
     * @return: 用户信息
     * @Author: wangze
     */
    @PostMapping("/login")
    public String userLogin(User user) throws AuthenticationException, JSONException {
//        System.out.println("用户登录");
        try {
            List<Object> list = userService.login(user.getUsername(), user.getPassword());
            String temp = loginSuccess(list, user);
            return temp;
        } catch (Exception e) {
            String temp = loginFail(user);
            return temp;
        }
    }

    /**
     * @Description: 登录成功的返回方法
     * @Param: list: 登录成功返回的用户信息
     * user: 前端传递的用户信息
     * @return: 返回给前端的用户信息
     * @Author: wangze
     */
    public String loginSuccess(List<Object> list, User user) {
        String token = (String) list.get(0);
        Integer user_id = (Integer) list.get(1);
        String auth = (String) list.get(2);
        String username = user.getUsername();
        String name = (String) list.get(3);
        String department = (String) list.get(4);
        String phone = (String) list.get(5);
        String sex = (String) list.get(6);
        Integer age = (Integer) list.get(7);
        Integer roleId = (Integer) list.get(8);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("token", token);
        jsonObject.put("user_id", user_id);
        jsonObject.put("auth", auth);
        jsonObject.put("username", username);
        jsonObject.put("name", name);
        jsonObject.put("department", department);
        jsonObject.put("phone", phone);
        jsonObject.put("sex", sex);
        jsonObject.put("age", age);
        jsonObject.put("roleId", (Integer) roleId);
//        log.info("用户{}登录成功。", ParseUsername.getUser());
        log.info("用户{}登录成功。", user.getUsername());
        return jsonObject.toString();
    }

    /**
     * @Description: 登录失败的返回方法
     * @Param:
     * @return: 登录失败的提示
     * @Author: wangze
     */
    public String loginFail(User user) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("token", "");
        jsonObject.put("msg", "用户名或密码错误");
        log.info("用户{}登陆失败", user);
        return jsonObject.toString();
    }

    /**
     * @Description: 用户修改密码
     * @Param:
     * @return:
     * @Author: wangze
     */
    @PreAuthorize("hasPermission('users','users:permissions:basic')")
    @PutMapping(value = "/user/password")
    public String changePassword(@RequestParam("user_id") Integer id, @RequestParam("oldpassword") String oldpassword, @RequestParam("newpassword") String newpassword) {
        User user1 = userService.getById(id);
        if (!bCryptPasswordEncoder.matches(oldpassword, user1.getPassword())) {
            return "旧密码错误，请重试";
        }
        user1.setPassword(bCryptPasswordEncoder.encode(newpassword));
        userService.updateUser(user1);
        log.info("用户" + user1.getUsername() + "修改密码成功。");
        return "修改成功";
    }

    //刷新token
    @GetMapping("/user/refreshtoken")
    public String tokenRefresh(@RequestParam("_token") String token) {
        return userService.refreshUserToken(token);
    }


}
